<?php

namespace app\tools;

use Yii;

class AliRefund
{
  //微信退款
  public static function refund($order, $money, $money_total) {
    $param["appid"] = $order->company->wechat_appid;
		$param["mch_id"] = $order->mch_id;
		$param["nonce_str"] = md5(time().rand().$order->order_sn_union);
		$param["out_trade_no"] = $order->order_sn_union;
		$param["out_refund_no"] = time().rand(0,9999);
		$param["total_fee"] = $money_total * 100; //金额单位:分
		$param["refund_fee"] = $money * 100; //金额单位:分
    $key = $order->mch_key;
		$sign = self::getSign($param, $key);
		$param["sign"] = $sign;
		$xml = self::ToXml($param);
		$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		$response = self::curl_refund($url, $xml, $param["mch_id"]);
		$res = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)));
		return $res;
  }

  public static function ToXml($param) {
		if(!is_array($param) || count($param) <= 0)
		{
				throw new WxPayException("数组数据异常！");
			}

			$xml = "<xml>";
			foreach ($param as $key=>$val)
			{
				if (is_numeric($val)){
					$xml.="<".$key.">".$val."</".$key.">";
				}else{
					$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
				}
				}
				$xml.="</xml>";
				return $xml;
	}

	public static function getSign($param, $key) {
		//签名步骤一：按字典序排序参数
		ksort($param);
		$string = self::ToUrlParams($param);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".$key;
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}

	/**
	 * 格式化参数格式化成url参数
	 */
	public static function ToUrlParams($param) {
		$buff = "";
		foreach ($param as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}

		$buff = trim($buff, "&");
		return $buff;
	}

	public static function curl_refund($url, $data, $mch_id)	{
		//echo getcwd();die;
		//echo Yii::$app->params['domain'].'/public/cert/apiclient_key.pem';die;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
		curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/public/cert/'.$mch_id.'/apiclient_cert.pem');
		curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
		curl_setopt($ch, CURLOPT_SSLKEY, getcwd().'/public/cert/'.$mch_id.'/apiclient_key.pem');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$data = curl_exec($ch);
		return $data;
	}
}
